<!--
 * @Descripttion: 出手鸭小程序
 * @version:1.0.1 
 * @Author: HHL
 * @Date: 2023-10-08 16:00:47
 * @LastEditTime: 2025-09-28 20:46:02
 * @LastEditors: sueRimn
-->

<template>
  <view class="product">
    <!-- #ifdef H5 -->
    <custom-navbar title="估价" />
    <!-- #endif -->
    <view class="header">
      <!-- 进度条 -->
      <progress-bar :step="step" :total="total" />

      <!-- 手机信息 -->
      <phone-info :productDetail="productDetail" />
    </view>
    <!-- 估价项目 -->
    <evaluate-list :mainHeight="mainHeight" :evaluateItems="evaluateItems" :step="step" :scrollIntoView="scrollIntoView"
      @onEvaluateClick="onEvaluateClick" />

    <!-- 底部按钮 -->
    <fixed-footer :systemInfo="systemInfo" :checkFinishQuestion="checkFinishQuestion" @onAssessClick="onAssessClick" />
	<!-- 拿钱攻略 -->
	<image src="https://image.chushouya.com/assets/images/product/img_xfc@2x.png" mode="aspectFill" class="strategy-guide" @click="goStrategyGuide"></image>
  </view>
</template>


<script>
import { mapGetters } from 'vuex'
import qs from 'qs'

import {
  fetchEvaluateProduct,
  fetchEvaluateItem,
  fetchEvaluateResult,
} from '@/api'
import goLogin from '@/utils/login'
import { waitShowToast,urlJump } from '@/utils'
import { callAppLogin, checkIsInApp } from '@/utils/appBridge.js'
import ProgressBar from './components/ProgressBar.vue'
import PhoneInfo from './components/PhoneInfo.vue'
import EvaluateList from './components/EvaluateList.vue'
import FixedFooter from './components/FixedFooter.vue'



export default {
  components: {
    ProgressBar, PhoneInfo, EvaluateList,
    FixedFooter
  },
  options: {
    styleIsolation: 'shared'
  },
  computed: {
    ...mapGetters([
      'systemInfo', 'userInfo',
    ]),
    mainHeight() {
      const windowHeight = this.systemInfo.windowHeight || 0
      const topHeight = 230

      const footerPadding = this.systemInfo.fullScreen ? 50 : 50

      const empty = 5 // 留白空间

      const height = windowHeight - (windowHeight / 1334 * (topHeight + footerPadding)) - empty

      return height
    },
    checkFinishQuestion() {
      return this.step === this.total
    },
    skuCode() {
      const result = this.valueList.filter(item => item.evaluateType == 1).map(item => item.attrId + ":" + item.valueId).join(',')
      return result
    },
    skuValueList() {
      return this.valueList.filter(item => item.evaluateType == 1).map(item => item.attrId + ":" + item.valueId)
    }
  },

  onLoad(options) {
    if (options.id) {
      this.id = options.id
      this.loadProductEvaluate()
    }
    this.params = options;
    // 检测是否在 APP 中
    this.isInCylApp = checkIsInApp()
  },

  onShow() {
    // 如果从登录页返回且需要执行估价
    if (this.pendingAssess && this.userInfo.userId) {
      this.onAssessClick()
    }
  },
  data() {
    return {
      params: {},
      pendingAssess: false, // 标记是否需要在登录后调用估价
      isInCylApp: false, // 是否在 cylApp 中

      id: '',
      productDetail: {
        productName: '',
        maxPrice: 0,
      }, // 商品信息

      // skuCode: '', // sku编码
      evaluateCode: '', // 估价编码
      skuId: 0, // skuId
      // skuValueList: [], // sku编码列表
      evaluateValueList: [], // 估价编码列表
      evaluateItems: [],//评估选项

      skuList: [], // sku列表
      evaluateList: [], // 估价列表

      step: 0,
      total: 0,

      scrollIntoView: '',
      valueList: []
    }
  },

  methods: {
    // 获取商品估价信息
    loadProductEvaluate() {
      try {
        uni.showLoading({ title: '加载中...', mask: true })
        fetchEvaluateProduct({ productId: this.id }).then(async ({ data, code }) => {
          // console.log('fetchEvaluateProduct', data)
          if (code === 200) {
            const evaluateList = data.evaluateList || []
            this.productDetail = data

            this.evaluateItems = [...evaluateList]
            this.skuList = evaluateList
            this.total = evaluateList.length
          }
        })
      } finally {
        uni.hideLoading()
      }
    },

    //加载SKU评估信息
    loadEvaluateItem() {
      try {
        uni.showLoading({ title: '加载中...', mask: true })
        fetchEvaluateItem({ productId: this.id, skuCode: this.skuCode }).then(async ({ data, code }) => {
          if (code === 200) {
            this.skuId = data.skuId
            const evaluateList = data.evaluateList || []
            const evaluateItems = [...this.skuList, ...evaluateList]
            this.evaluateItems = evaluateItems
            let evaluateItemsLength = evaluateList.filter(item => !item.isMultiSelect).length
            this.evaluateList = evaluateList
            this.step = this.skuList.length
            this.total = this.skuList.length + evaluateItemsLength
          }
        })
      } finally {
        uni.hideLoading()
      }
    },


    // 估价点击
    onAssessClick() {
      if (!this.checkFinishQuestion) { return }

      if (!this.userInfo.userId) {
        this.pendingAssess = true // 设置标志位
        // 如果在 APP 中，调用 APP 登录
        if (this.isInCylApp) {
          this.handleAppLogin()
          return
        }
        goLogin()
        return
      }

      this.pendingAssess = false // 清除标志位

      uni.showLoading({
        title: '估价中...',
        mask: true
      })
      const payload = {
        productId: this.id,
        skuId: this.skuId,
        skuCode: this.skuCode,
        evaluateCode: this.getEvaluateCode(),
      }

      try {
        fetchEvaluateResult(payload).then(({ data, code, message }) => {
          if (code === 200) {
            console.log('evaluateResult 返回结果', data)
            this.$store.dispatch('evaluate/updateEvaluateInfo', data)
            this.finishJump()
          } else {
            waitShowToast(message)
            if (code === 401) {
              this.goLogin()
            }
          }
        })

      } finally {

      }
    },


    // 估价项目点击
    onEvaluateClick(
      step, valueList,
    ) {
      this.step = step
      this.valueList = [...valueList]
      this.handleMoveItem(`attr-item-${step - 1}`)
      if (valueList.length === this.skuList.length) {
        // this.skuValueList = valueList
        // this.getSkuCode()
        // this.loadEvaluateItem()
      }
      if (valueList.length > this.skuList.length) {
        this.evaluateValueList = [...valueList.slice(this.skuList.length, this.valueList.length)]
        // console.log('evaluateValueList', this.evaluateValueList)
      }
    },

    //组合skuCode
    getSkuCode() {
      // let skuCode = this.skuValueList.map(item => item.attrId + ":" + item.valueId).join(',')
      // this.skuCode = skuCode
      // return skuCode
    },
    //组合evaluateCode
    getEvaluateCode() {
      let evaluateCode = this.evaluateValueList.map(item => item.attrId + ":" + item.valueId).join(',')
      this.evaluateCode = evaluateCode
      return evaluateCode
    },


    // 移动项目
    handleMoveItem(target) {
      this.scrollIntoView = target
    },


    // 完成跳转
    finishJump() {
      uni.navigateTo({ url: `/pages/assess/index?${qs.stringify({ from: this.params.from })}` })
    },
	
	// 跳转攻略
	goStrategyGuide(){
	  uni.navigateTo({
		url: "/pages/help/index"
	  })
	},

    // 调用 APP 登录
    async handleAppLogin() {
      try {
        uni.showLoading({ title: '登录中...' })
        const result = await callAppLogin({
          from: 'product-assess',
          timestamp: Date.now()
        })
        uni.hideLoading()
        
        console.log('[Product] APP 登录成功:', result)
        
        // 处理登录结果
        if (result) {
          // 保存 token
          uni.setStorageSync('token', result)
          getApp().globalData.token = result
          // 重新加载用户信息
          await this.$store.dispatch('user/loadUserInfo')
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          // 登录成功后自动执行估价
          if (this.pendingAssess) {
            setTimeout(() => {
              this.onAssessClick()
            }, 500)
          }
        }
      } catch (error) {
        uni.hideLoading()
        console.error('[Product] APP 登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        })
      }
    }
  },
  watch: {
    // 监听step变化
    skuCode(newVal, oldVal) {
      
      if (this.skuValueList.length === this.skuList.length) {
        // console.log('条件满足，调用 loadEvaluateItem()')
        this.loadEvaluateItem()
      } else {
        // console.log('条件不满足，不调用 loadEvaluateItem()')
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.product {
  background: #F4F5F7;
    /* #ifdef H5 */
  padding-top: calc(var(--status-bar-height) + 88rpx);
  /* #endif */
  .strategy-guide {
	  width: 64rpx;
	  height: 178rpx;
	  position: fixed;
	  left: 0;
	  bottom: 286rpx;
	  z-index: 2;
  }
  .header {
    padding: 0rpx 0rpx;
  }
}
</style>
